const express = require('express');
const CryptoJs = require('crypto-js');
const UserModel = require('../models/user');
const customerInfoModel = require('../models/customerInfo');
const { Message,MessageList } = require('../utils/message');

const router = express.Router();

router.post('/',(req, res, next) => {
  const {username, password} = req.body;
  if(username&&password){
    UserModel.find({username}).then(data => {
      if(data.length > 0){
        res.json(Message(400,'该用户已被注册！'));
        return
      }
      const passwordHash = CryptoJs.MD5(password);
      const user = new UserModel({username, password: passwordHash,role: 'normal'});
      user.save().then(data => {
        const userMsg = {...data._doc}
        delete userMsg.password
        res.json(Message(200,'注册成功！',userMsg));
        const customerInfo = new customerInfoModel({ username, sex: '', name: '', phone: '',address: '',userType: 0,discount: 1,registDate: new Date(), 
          carInfo: { brand: '',model: '',color: '',carId: ''}
        });
        customerInfo.save();
      });
      
    });
  }else{
    res.json(Message(400,'注册失败！'));
  }
});
module.exports = router;